package com.squirrel.michale;

import java.util.Arrays;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/2/17 7:25 AM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class LeetCode2563 {

    public long countFairPairs(int[] nums, int lower, int upper) {
        Arrays.sort(nums);
        return pairsCountLessThanK(nums, upper) - pairsCountLessThanK(nums, lower - 1);
    }


    private long pairsCountLessThanK(int[] nums,int k) {
        int left = 0;
        int right = nums.length - 1;

        long pairsCount = 0;
        while (left < right) {
            int fairSum = nums[left] + nums[right];
            if (fairSum <= k) {
                pairsCount += right - left;
                left++;
            }else {
                right--;
            }
        }
        return pairsCount;
    }


    public long countFairPairs2(int[] nums, int lower, int upper) {

        int left = 0;
        int right = nums.length - 1;

        int pairsCount = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                int fairSum = nums[i] + nums[j];
                if (fairSum >= lower && fairSum <= upper) {
                    pairsCount++;
                }
            }
        }
        return pairsCount;

    }


    public long countFairPairs3(int[] nums, int lower, int upper) {

        Arrays.sort(nums);



        int left = 0;
        int right = nums.length - 1;

        int pairsCount = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                int fairSum = nums[i] + nums[j];
                if (fairSum >= lower && fairSum <= upper) {
                    pairsCount++;
                }
            }
        }
        return pairsCount;

    }
}
